package my.mall.common.util

import com.auth0.jwt.JWT
import com.auth0.jwt.JWTVerifier
import com.auth0.jwt.algorithms.Algorithm
import java.time.LocalDateTime
import java.util.*

object JwtUtils {

    private val algorithm: Algorithm = Algorithm.HMAC256("ajfaljawohlakj2qr0@)U$05ru20u)ur)qejjgoiporju)uajaup120LJFAPP240280U4101!#)u!)gqhipt")
    private val header: Map<String, Any> = mapOf("typ" to "JWT", "alg" to "HS256");
    private val verifier: JWTVerifier = JWT.require(algorithm).build()

    fun createToken(id: Long?): String {
        val expireDate = LocalDateTime.now().plusHours(2)
        return createToken(id, DateUtils.asDate(expireDate))
    }

    fun createToken(id: Long?, expireTime: Date?): String {
        return JWT.create() // 设置头部信息 Header
            .withHeader(header) // 设置 载荷 Payload
            .withClaim("id", id) // 生成签名的时间
            .withIssuedAt(Date()) // 签名过期的时间
            .withExpiresAt(expireTime) // 签名Signature
            .sign(algorithm)
    }

    fun verifyToken(token: String?): Long {
        val jwt = verifier.verify(token)
        val claims = jwt.claims
        val claim = claims["id"]
        return claim!!.asLong()
    }
}
